var express = require('express'),fs = require('fs');
var wechat = require('wechat');
var WechatAPI = require('wechat-api');
var OAuth = require('wechat-oauth');
var async = require('async');
var moment = require('moment');

var Model = require('../model');

var Message = Model.Message, Fans = Model.Fans, FansToken = Model.FansToken;

moment.locale('zh_cn');

/*
 * Module dependencies
 */
/**
 * Expose routes
 */

module.exports = Routes;

/**
 * Defines routes for application
 *
 * @param {Express} app `Express` instance.
 * @api public
 */

function Routes (app) {

	var config = app.get('config');

	var perpage = config.env.perpage;

	var spreadUrl = config.env.spreadurl;

	var router = express.Router();

	var weToken = {
		token: config.weixin.access.token,
		appid: config.weixin.appid,
		encodingAESKey: config.weixin.access.encodingAESKey
	}

	var appid = config.weixin.appid;
	var appsecret = config.weixin.appsecret;

	//获取access_token
	var api = new WechatAPI(appid, appsecret, function (callback) {
		// 传入一个获取全局token的方法
		fs.readFile('./data/access_token.txt', 'utf8', function (err, txt) {
			if (err) {
				return callback(err);
			}
			//access_token.txt 第一次必须有值否则要传一个空的json 字符串
			callback(null, JSON.parse(txt));
		});
	}, function (token, callback) {
		fs.writeFile('./data/access_token.txt', JSON.stringify(token), callback);
	});

	var oauthApi = new OAuth(appid, appsecret, function (openid, callback) {
		// 传入一个根据openid获取对应的全局token的方法
		FansToken.findOne({openid: openid}).exec(function (err, fstoken) {
			if (err) {return callback(err);}

			var token = {
				openid: fstoken.openid,
				access_token: fstoken.access_token,
				expires_in: fstoken.expires_in,
				refresh_token: fstoken.refresh_token,
				scope: fstoken.scope,
				create_at: fstoken.created_at*1000
			}
			callback(null, token);
		})
	}, function (openid, token, callback) {
		// token写到mongodb数据库
		// 每个openid都对应一个唯一的token!
		FansToken.findOne({openid: openid}).exec(function (err, fstoken) {
			if(fstoken) {
				fstoken.access_token = token.access_token;
				fstoken.expires_in = token.expires_in;
				fstoken.refresh_token = token.refresh_token;
				fstoken.scope = token.scope;
				fstoken.save(callback);
			}
			else {
				token.created_at = token.create_at/1000;
				FansToken.create(token, callback);
			}
		});

	});


	//微信接入的url 消息处理路由
	router.all('/wechat', wechat(weToken,
		wechat.event(function (message, req, res, next) {
			//微信事件处理 首先查找用户
			Fans.findOne({ openid: message.FromUserName }).exec(function (err, fans) {
				//订阅
				if( message.Event == 'subscribe' ){
					//从微信接口读取用户信息直接入库
					api.getUser(message.FromUserName, function(err, wxfans) {
						if( fans ) {
						// 有粉丝 更新粉丝信息
							fans.subscribe = 1;
							fans.headimgurl = wxfans.headimgurl;
							fans.nickname = wxfans.nickname;
							fans.subscribe_time = wxfans.subscribe_time;
							fans.save(function(err,resu){})
						}
						else { //没有粉丝 创建粉丝入库

							Fans.findOne().sort({ unique_id: -1 }).exec(function (err, lastFans) {
								wxfans.unique_id =  (!lastFans)? 0: (lastFans.unique_id + 1),
								wxfans.created_at = moment().unix();
								Fans.create(wxfans, function(err, insertedFans){});
							})

						}
						res.reply('您好，亲爱的朋友，感谢您的关注，这里记录着郭晟先生和余杨女士爱情的点点滴滴，看完我们的爱情故事之后就赶紧给我们送上祝福吧！');
					});
				} //取消订阅
				else if ( message.Event == 'unsubscribe' ) {
					if(fans) {
						fans.subscribe = 0;
						fans.save(function(err,resu){})
					}
					res.reply('再见');
				}
			});
		}).text(function (message, req, res, next) {
			res.reply('您的消息已收到，主人看到会即时恢复您的哦！');
		})
	));


	//创建菜单 菜单内容写成本地文件
	router.get('/wechat/menu/create',  function(req, res){

		api.createMenu(config.menu, function(err, result){
			res.writeHead(200);
			if(err){
				console.log(err);
				res.end('change menu error!');
			}
			else{
				res.end('success!');
			}
		});

	});


	//oauth认证身份回调页面
	router.get('/transfer',  function(req, res){
		//获取access_token 和open_id 到此结束
		oauthApi.getAccessToken(req.query.code, function (err, result) {
			if( !req.query.code ) {
				res.writeHead(200);
				res.end('request error, please retry!');
				return;
			}
			var accessToken = result.data.access_token;
			var openid = result.data.openid;

			//获取openid 查数据库
			Fans.findOne({ openid: openid }).exec(function (err, fans) {
				//从微信接口读取用户信息直接入库
				api.getUser(openid, function(err, wxfans) {
					//已关注该公众号
					if( wxfans.subscribe == 1 ) {
						//更新粉丝信息
						if(fans){
							fans.subscribe = wxfans.subscribe;
							fans.headimgurl = wxfans.headimgurl;
							fans.nickname = wxfans.nickname;
							fans.save(function(err,resu){
								//用户信息存入session
								req.session.fans = fans;
								//回调到请求来源url
								res.redirect(req.query.returnUrl);
							})
						}
						else{
							//新建粉丝
							Fans.findOne().sort({ unique_id: -1 }).exec(function (err, lastFans) {
								wxfans.unique_id =  (!lastFans)? 0: (lastFans.unique_id + 1),
								wxfans.created_at = moment().unix();
								Fans.create(wxfans, function(err, insertedFans){
									//用户信息存入session
									req.session.fans = insertedFans;
									//回调到请求来源url
									res.redirect(req.query.returnUrl);
								});
							})
						}
					}
					else {
					//未关注 跳转关注
						res.redirect(spreadUrl);
					}
				})
			});
		});

	});


	// 访问公众号页面经过此处过滤
	router.use('/marryme', function(req, res, next) {

		app.locals.perpage = perpage;

		var weixinAgentReg = /MicroMessenger/;

		if( !weixinAgentReg.test(req.headers['user-agent']) ){
			//pc 访问 直接跳转到转发页面 测试用
/*
			Fans.findOne({ openid: 'om92ixEH3EqcSdm_9ZDSJRzEoJss' }).exec(function (err, fans) {
				//req.session.fans = fans;
				app.locals.fans = fans;
				next();
			})
*/
			res.redirect(spreadUrl);

		}

		if( !req.session.fans ) {

			var returnUrl = req.originalUrl;
			// 没有通过身份认证 oauth 微信网页授权
			var oauthUrl = oauthApi.getAuthorizeURL('http://wechat.jiayu77.com/transfer?returnUrl='+returnUrl, '123', 'snsapi_base');
			//跳转到 https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 获取code
			res.redirect(oauthUrl);

		}
		else {
			//console.log(req.session.fans);
			app.locals.fans = req.session.fans;
			next();
		}


	});


	router.get('/marryme/lovestory', function(req, res) {
		var pageid = req.query.p;
		var title = '这一路走来，幸福与甜蜜因为有你相伴！！';
		if(pageid)
			res.render('lovestory_'+pageid, { title: title , moment: moment});
		else
			res.render('lovestory', { title: title , moment: moment});
	});


	router.get('/marryme/blessing', function(req, res) {

		Message.find().populate('fans').sort({unique_id:-1}).limit(perpage).exec(function(err, msg){
			Message.count({}, function (err, count) {
				res.render('blessing', { msgData: msg , msgCount: count, moment: moment});
			});
		});

	});

	router.get('/marryme/about', function(req, res) {

		res.render('about', {moment: moment});

	});

	app.use(router);

}
